package com.yhkj.data.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.yhkj.data.mq.enums.JdbcMessageEnum;
import com.yhkj.data.mq.message.DataSourceConfig;
import com.yhkj.data.mq.message.SyncMessage;
import com.yhkj.data.mq.message.TableMetaData;
import org.apache.commons.lang3.ArrayUtils;

import java.io.IOException;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-03-06 15:42:55
 */
public class SyncMessageDeserializer extends JsonDeserializer<SyncMessage> {
    @Override
    public SyncMessage deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
        JsonNode tree = mapper.readTree(jsonParser);
        SyncMessage result = new SyncMessage();
        // 获取列类型数组
        result.setDataSourceConfig(mapper.treeToValue(tree.get("dataSourceConfig"), DataSourceConfig.class));
        TableMetaData tableMetaData = mapper.treeToValue(tree.get("tableMetaData"), TableMetaData.class);
        result.setTableMetaData(tableMetaData);
        if (tableMetaData == null || ArrayUtils.isEmpty(tableMetaData.getTypes())) {
            return result;
        }
        ArrayNode arrayNode = (ArrayNode) tree.get("data");
        if (arrayNode.isEmpty()) {
            return result;
        }
        int typeSize = result.getTableMetaData().getTypes().length;
        JdbcMessageEnum[] jdbcMessageEnums = new JdbcMessageEnum[typeSize];
        Object[][] data = new Object[arrayNode.size()][typeSize];
        for (int i = 0, rowSize = arrayNode.size(); i < rowSize; i++) {
            ArrayNode rowArrayNode = (ArrayNode) arrayNode.get(i);
            for (int j = 0; j < typeSize; j++) {
                if (i == 0) {
                    jdbcMessageEnums[j] = JdbcMessageEnum.getInstance(tableMetaData.getTypes()[j]);
                }
                data[i][j] = jdbcMessageEnums[j] == null || rowArrayNode.get(j) instanceof NullNode ?
                        // todo 通过JdbcMessageEnum类型，调用JsonNode对应方法取值并转换，而不是所有值都转成String再进行parseValue
                        null : jdbcMessageEnums[j].parseValue(rowArrayNode.get(j).asText());
            }
        }
        result.setData(data);
        // 根据列类型反序列化
        return result;
    }

    private Object parseValue(JdbcMessageEnum jdbcMessageEnum, JsonNode jsonNode) {
        return null;
    }
}
